package com.alpha.module.sys.service.impl;

import com.alpha.module.sys.dao.SysUserMapper;
import com.alpha.module.sys.dao.SysUserRoleMapper;
import com.alpha.module.sys.entity.SysUser;
import com.alpha.module.sys.entity.SysUserRole;
import com.alpha.module.sys.model.SysUserDTO;
import com.alpha.module.sys.service.SysUserService;
import com.alpha.common.utils.BusinessException;
import com.alpha.common.utils.PageUtils;
import com.alpha.common.utils.SecurityUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service("sysUserService")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Override
    public PageUtils queryPage(SysUserDTO vo) {
        PageHelper.startPage(vo.getPageNo(), vo.getPageSize());
        List<SysUserDTO> list = this.sysUserMapper.queryJoinList(vo);
        for (SysUserDTO sysUserDTO : list) {
            List<SysUserRole> userRoles = sysUserRoleMapper.selectRolesByUserId(sysUserDTO.getId());
            sysUserDTO.setUserRoles(userRoles);
        }
        return new PageUtils(new PageInfo<>(list));
    }

    @Override
    public void save(SysUser sysUser) {
        sysUser.setCreateTime(new Date());
        sysUser.setCredential(SecurityUtil.MD5(sysUser.getCredential() + "a@n#t$d%321" ));
        sysUserMapper.insertSelective(sysUser);
    }

    @Override
    public SysUser getById(Long id) {
        if (id <= 0) {
            throw new BusinessException("参数错误");
        }
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public void updateById(SysUser sysUser) {
        sysUser.setModifyTime(new Date());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public SysUser login(SysUserDTO vo) {
        vo.setCredential(SecurityUtil.MD5(vo.getCredential() + "a@n#t$d%321"));
        SysUser sysUser = sysUserMapper.selectByCredential(vo);
        if (sysUser == null) {
            throw new BusinessException("账号或密码错误");
        }
        if (sysUser.getState() != 1) {
            throw new BusinessException("此账户已被限制登录");
        }
        return sysUser;
    }


}